import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:family_app/src/theme/app_theme.dart';

/// 折线图 - 收支趋势
/// 显示一段时间内的收入和支出趋势
class TrendChart extends StatelessWidget {
  /// 支出数据列表
  final List<double> expenseData;

  /// 收入数据列表
  final List<double> incomeData;

  /// 图表标题
  final String? title;

  const TrendChart({
    Key? key,
    required this.expenseData,
    required this.incomeData,
    this.title,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (title != null)
          Padding(
            padding: EdgeInsets.only(bottom: 12.h),
            child: Text(
              title!,
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        SizedBox(
          height: 300.h,
          child: LineChart(
            LineChartData(
              gridData: FlGridData(
                show: true,
                drawVerticalLine: true,
                horizontalInterval: 1,
                verticalInterval: 1,
              ),
              titlesData: FlTitlesData(
                bottomTitles: AxisTitles(
                  sideTitles: SideTitles(
                    showTitles: true,
                    getTitlesWidget: (value, meta) {
                      const titles = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
                      if (value.toInt() < titles.length) {
                        return Text(
                          titles[value.toInt()],
                          style: TextStyle(fontSize: 10.sp),
                        );
                      }
                      return const SizedBox.shrink();
                    },
                  ),
                ),
                leftTitles: AxisTitles(
                  sideTitles: SideTitles(
                    showTitles: true,
                    getTitlesWidget: (value, meta) {
                      return Text(
                        '¥${value.toInt()}',
                        style: TextStyle(fontSize: 10.sp),
                      );
                    },
                  ),
                ),
              ),
              lineBarsData: [
                // 支出线
                LineChartBarData(
                  spots: expenseData
                      .asMap()
                      .entries
                      .map((e) => FlSpot(e.key.toDouble(), e.value))
                      .toList(),
                  isCurved: true,
                  color: Colors.red,
                  barWidth: 2,
                  dotData: FlDotData(
                    show: true,
                    getDotPainter: (spot, percent, barData, index) {
                      return FlDotCirclePainter(
                        radius: 4,
                        color: Colors.red,
                        strokeWidth: 2,
                        strokeColor: Colors.white,
                      );
                    },
                  ),
                  belowBarData: BarAreaData(
                    show: true,
                    color: Colors.red.withOpacity(0.1),
                  ),
                ),
                // 收入线
                LineChartBarData(
                  spots: incomeData
                      .asMap()
                      .entries
                      .map((e) => FlSpot(e.key.toDouble(), e.value))
                      .toList(),
                  isCurved: true,
                  color: Colors.green,
                  barWidth: 2,
                  dotData: FlDotData(
                    show: true,
                    getDotPainter: (spot, percent, barData, index) {
                      return FlDotCirclePainter(
                        radius: 4,
                        color: Colors.green,
                        strokeWidth: 2,
                        strokeColor: Colors.white,
                      );
                    },
                  ),
                  belowBarData: BarAreaData(
                    show: true,
                    color: Colors.green.withOpacity(0.1),
                  ),
                ),
              ],
            ),
          ),
        ),
        // 图例
        Padding(
          padding: EdgeInsets.only(top: 12.h),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _buildLegendItem('支出', Colors.red),
              SizedBox(width: 24.w),
              _buildLegendItem('收入', Colors.green),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建图例项
  Widget _buildLegendItem(String label, Color color) {
    return Row(
      children: [
        Container(
          width: 12.w,
          height: 12.w,
          decoration: BoxDecoration(
            color: color,
            shape: BoxShape.circle,
          ),
        ),
        SizedBox(width: 6.w),
        Text(
          label,
          style: TextStyle(fontSize: 12.sp),
        ),
      ],
    );
  }
}

/// 饼图 - 分类统计
/// 显示各分类的支出占比
class CategoryPieChart extends StatefulWidget {
  /// 分类数据（分类名 -> 金额）
  final Map<String, double> categoryData;

  /// 图表标题
  final String? title;

  const CategoryPieChart({
    Key? key,
    required this.categoryData,
    this.title,
  }) : super(key: key);

  @override
  State<CategoryPieChart> createState() => _CategoryPieChartState();
}

class _CategoryPieChartState extends State<CategoryPieChart> {
  /// 当前触摸的饼图索引
  int touchedIndex = -1;

  @override
  Widget build(BuildContext context) {
    final total = widget.categoryData.values.fold(0.0, (a, b) => a + b);
    final sections = widget.categoryData.entries
        .toList()
        .asMap()
        .entries
        .map((e) {
          final percentage = (e.value.value / total * 100);
          return PieChartSectionData(
            value: e.value.value,
            title: '${percentage.toStringAsFixed(1)}%',
            radius: touchedIndex == e.key ? 60 : 50,
            titleStyle: TextStyle(
              fontSize: 11.sp,
              fontWeight: FontWeight.bold,
              color: Colors.white,
            ),
            color: _getCategoryColor(e.key),
          );
        })
        .toList();

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (widget.title != null)
          Padding(
            padding: EdgeInsets.only(bottom: 12.h),
            child: Text(
              widget.title!,
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        SizedBox(
          height: 300.h,
          child: PieChart(
            PieChartData(
              sections: sections,
              centerSpaceRadius: 40,
              sectionsSpace: 2,
              pieTouchData: PieTouchData(
                touchCallback: (FlTouchEvent event, pieTouchResponse) {
                  setState(() {
                    touchedIndex = pieTouchResponse?.touchedSection?.touchedSectionIndex ?? -1;
                  });
                },
              ),
            ),
          ),
        ),
        // 分类列表
        Padding(
          padding: EdgeInsets.only(top: 12.h),
          child: Column(
            children: widget.categoryData.entries
                .toList()
                .asMap()
                .entries
                .map((e) {
                  final percentage = (e.value.value / total * 100);
                  return Padding(
                    padding: EdgeInsets.only(bottom: 8.h),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Row(
                          children: [
                            Container(
                              width: 12.w,
                              height: 12.w,
                              decoration: BoxDecoration(
                                color: _getCategoryColor(e.key),
                                shape: BoxShape.circle,
                              ),
                            ),
                            SizedBox(width: 8.w),
                            Text(
                              e.value.key,
                              style: TextStyle(fontSize: 12.sp),
                            ),
                          ],
                        ),
                        Text(
                          '¥${e.value.value.toStringAsFixed(0)} (${percentage.toStringAsFixed(1)}%)',
                          style: TextStyle(
                            fontSize: 12.sp,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                  );
                })
                .toList(),
          ),
        ),
      ],
    );
  }

  /// 获取分类颜色
  Color _getCategoryColor(int index) {
    final colors = [
      Colors.red,
      Colors.orange,
      Colors.yellow,
      Colors.green,
      Colors.blue,
      Colors.indigo,
      Colors.purple,
      Colors.pink,
    ];
    return colors[index % colors.length];
  }
}

/// 环形图 - 预算进度
/// 显示预算的使用进度
class BudgetRingChart extends StatelessWidget {
  /// 已支出金额
  final double spent;

  /// 预算总额
  final double budget;

  /// 图表标题
  final String? title;

  const BudgetRingChart({
    Key? key,
    required this.spent,
    required this.budget,
    this.title,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final percentage = (spent / budget * 100).clamp(0, 100);
    final isOverBudget = spent > budget;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (title != null)
          Padding(
            padding: EdgeInsets.only(bottom: 12.h),
            child: Text(
              title!,
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        Center(
          child: SizedBox(
            width: 200.w,
            height: 200.w,
            child: Stack(
              alignment: Alignment.center,
              children: [
                // 环形进度条
                CircularProgressIndicator(
                  value: (percentage / 100).clamp(0, 1),
                  strokeWidth: 12.w,
                  backgroundColor: Colors.grey.withOpacity(0.2),
                  valueColor: AlwaysStoppedAnimation<Color>(
                    isOverBudget || percentage > 80 ? Colors.red : AppTheme.primaryColor,
                  ),
                ),
                // 中心文字
                Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      '${percentage.toStringAsFixed(1)}%',
                      style: TextStyle(
                        fontSize: 32.sp,
                        fontWeight: FontWeight.bold,
                        color: isOverBudget || percentage > 80 ? Colors.red : Colors.black,
                      ),
                    ),
                    SizedBox(height: 4.h),
                    Text(
                      '¥${spent.toStringAsFixed(0)} / ¥${budget.toStringAsFixed(0)}',
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: Colors.grey[600],
                      ),
                    ),
                    if (isOverBudget)
                      Padding(
                        padding: EdgeInsets.only(top: 4.h),
                        child: Text(
                          '已超支 ¥${(spent - budget).toStringAsFixed(0)}',
                          style: TextStyle(
                            fontSize: 11.sp,
                            color: Colors.red,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }
}

/// 柱状图 - 年度对比
/// 显示各月份的支出对比
class BarChartWidget extends StatelessWidget {
  /// 月份数据列表
  final List<double> data;

  /// 图表标题
  final String? title;

  const BarChartWidget({
    Key? key,
    required this.data,
    this.title,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (title != null)
          Padding(
            padding: EdgeInsets.only(bottom: 12.h),
            child: Text(
              title!,
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        SizedBox(
          height: 300.h,
          child: BarChart(
            BarChartData(
              barGroups: data
                  .asMap()
                  .entries
                  .map((e) => BarChartGroupData(
                    x: e.key,
                    barRods: [
                      BarChartRodData(
                        toY: e.value,
                        color: AppTheme.primaryColor,
                        width: 12.w,
                        borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(4.r),
                          topRight: Radius.circular(4.r),
                        ),
                      ),
                    ],
                  ))
                  .toList(),
              titlesData: FlTitlesData(
                bottomTitles: AxisTitles(
                  sideTitles: SideTitles(
                    showTitles: true,
                    getTitlesWidget: (value, meta) {
                      const months = [
                        '1月', '2月', '3月', '4月', '5月', '6月',
                        '7月', '8月', '9月', '10月', '11月', '12月'
                      ];
                      if (value.toInt() < months.length) {
                        return Text(
                          months[value.toInt()],
                          style: TextStyle(fontSize: 10.sp),
                        );
                      }
                      return const SizedBox.shrink();
                    },
                  ),
                ),
                leftTitles: AxisTitles(
                  sideTitles: SideTitles(
                    showTitles: true,
                    getTitlesWidget: (value, meta) {
                      return Text(
                        '¥${value.toInt()}',
                        style: TextStyle(fontSize: 10.sp),
                      );
                    },
                  ),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}
